# -*- coding: utf-8 -*-
'''
Created on 30/set/2009

@author: syn
'''

import hashlib
import gtk

from ui.GladeBase import GladeBase
from ui import *
from soap import *

class Login(GladeBase):    
    def __init__(self):
        GladeBase.__init__(self, 'login_window')
        self.user = None
    
    def _retrieve_components(self):
        self.user_entry = self.builder.get_object('user_entry')
        self.password_entry = self.builder.get_object('password_entry')
    
    def run(self):
        while True:
            response = self.root_component.run()
            if response != 0:
                break
        return response
        
    def response(self, response_id):
        self.root_component.response(response_id)
    
    # Signals callbacks
    def on_connect_button_clicked(self, object, data=None):
        user = unicode(self.user_entry.get_text())
        passwd = self.password_entry.get_text()
        
        if not user or not passwd:
            get_warning_dialog(self.root_component, "Insert username and password")
        
        try:
            # calling server asking for login
            self.user = client.user_login(user, hashlib.md5(passwd).hexdigest())
        except Exception as e:
            get_error_dialog(self.root_component, e.message)
            return
        
        if self.user.id < 0:
            get_warning_dialog(self.root_component, "Refused connection. Username and/or password may be wrong")
            return
        
        if not self.user.active:
            get_error_dialog(self.root_component, "User has been disabled. Contact administrator")
            return
        
        self.response(gtk.RESPONSE_OK)